package com.hex.ds.hdrs.warn.service;

import com.hex.ds.hdrs.common.constant.Const;
import com.hex.ds.hdrs.common.utils.BaseUtil;
import com.hex.ds.hdrs.warn.dao.WarnConfRegionDao;
import com.hex.ds.hdrs.warn.dto.WarnConfDto;
import com.hex.ds.hdrs.warn.po.WarnConfRegion;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class WarnConfRegionService {

    @Autowired
    private WarnConfRegionDao warnConfRegionDao;

    /**
     * 添加
     * @param warnConfDto
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void add(WarnConfDto warnConfDto) {
        WarnConfRegion warnConfRegion = new WarnConfRegion();
        if (warnConfDto.getRegionJsonList() != null) {
            for (String agentCode : warnConfDto.getRegionJsonList()) {
                warnConfRegion.setPkId(BaseUtil.getPkId());
                warnConfRegion.setConfId(warnConfDto.getPkId());
                warnConfRegion.setType(Const.IS_AGENT);
                if (Const.TASK_RUN_END_NOTIC.equals(warnConfDto.getType()) || Const.TASK_APPOINT_TIME_NO_FINISH.equals(warnConfDto.getType())
                        || Const.TASK_RUNNING_TIME_OUT.equals(warnConfDto.getType())){
                    String type = ("2".equals(warnConfDto.getIsRegionAll()))?Const.IS_CYCLE_TASK:Const.IS_CRON_TASK;
                    warnConfRegion.setType(type);
                }
                warnConfRegion.setVal1(agentCode);
                this.warnConfRegionDao.add(warnConfRegion);
            }
        }
        if (warnConfDto.getToUserList() != null) {
            for (Integer userId : warnConfDto.getToUserList()) {
                warnConfRegion.setPkId(BaseUtil.getPkId());
                warnConfRegion.setConfId(warnConfDto.getPkId());
                warnConfRegion.setType(Const.IS_USER);
                warnConfRegion.setVal1(Integer.toString(userId));
                this.warnConfRegionDao.add(warnConfRegion);
            }
        }
    }

    /**
     * 根据confId删除
     *
     * @param confId
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void del(String confId) {
        log.debug("【WarnConfRegionService的del】confId={}" , confId);
        this.warnConfRegionDao.del(confId);
    }

    /**
     * 修改
     *
     * @param warnConfDto
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void edit(WarnConfDto warnConfDto) {
        log.debug("【WarnConfRegionService的edit】warnConfDto={}" , warnConfDto);
        this.del(warnConfDto.getPkId());
        this.add(warnConfDto);
    }
}
